#include "card.h"
#include "ui_card.h"
#include "log.h"
#include "bill.h"
#include "widget.h"
#include <QTextCodec>
#include <QMessageBox>
Card::Card(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Card)
{
    ui->setupUi(this);
}

Card::~Card()
{
    delete ui;
}
//将传入的指针 w 赋值给 widget，这样 Card 对象就持有了对传入 Widget 对象的引用
void Card::setWidget(Widget *w)
{
    widget = w;
}

void Card::setLog(Log *l)
{
    log = l;
}

void Card::setBill(Bill *b)
{
    bill = b;
}
void Card::setNetworkManager(NetworkManager *manager)
{
    networkManager = manager;
}

//点击跳转到主页界面
void Card::on_pushButton_home_clicked()
{
    widget->show();
    this->hide();
}
//点击跳转到日志界面
void Card::on_pushButton_log_clicked()
{
    log->show();
    this->hide();
}
//点击跳转到账单界面
void Card::on_pushButton_bill_clicked()
{
    bill->show();
    this->hide();
}

//发送登记指令和信息
void Card::on_pushButton_registered_clicked()
{
    // 获取各个编辑框中的文本信息
    QString user = ui->lineEdit_user->text();
    QString phone = ui->lineEdit_phone->text();
    QString license = ui->lineEdit_license->text();
    QString days = ui->lineEdit_days->text();

    // 按照指定格式组合信息数据
    QString dataString = QString("USER|%1|PHONE_NUMBER|%2|LICENSE_NUMBER|%3|DAYS|%4|")
            .arg(user)
            .arg(phone)
            .arg(license)
            .arg(days);

    // 计算详细数据的长度
    int len = dataString.toUtf8().size();

    QString lengthPrefix = QString("REGISTERED|%1|").arg(len); // 构建包含长度信息的前缀

    QByteArray prefixToSend = lengthPrefix.toUtf8();// 将前缀转换为 QByteArray
    QByteArray dataToSend = dataString.toUtf8();// 将后面的内容转换为 QByteArray

    networkManager->sendData(prefixToSend);// 先发送长度前缀命令
    // 调试
    qDebug() << "Sent prefix:" << prefixToSend;
    networkManager->sendData(dataToSend); // 再发送后面的内容
    // 调试
    qDebug() << "Sent data:" << dataToSend;
}

//发送充值指令和信息
void Card::on_pushButton_recharge_clicked()
{
    QString phone = ui->lineEdit_phone->text();
    QString days = ui->lineEdit_days->text();

    QString dataString = QString("PHONE_NUMBER|%1|DAYS|%2|")
            .arg(phone)
            .arg(days);

    int len = dataString.toUtf8().size();
    QString lengthPrefix = QString("RECHARGE|%1|").arg(len);

    QByteArray prefixToSend = lengthPrefix.toUtf8();
    QByteArray dataToSend = dataString.toUtf8();

    networkManager->sendData(prefixToSend);
    //调试
    qDebug() << "Sent prefix:" << prefixToSend;
    networkManager->sendData(dataToSend);
    // 调试
    qDebug() << "Sent data:" << dataToSend;
}
//发送获取剩余天数指令
void Card::on_pushButton_remaining_days_clicked()
{
    QString phone = ui->lineEdit_phone->text();

    QString dataString = QString("PHONE_NUMBER|%1|").arg(phone);

    int len = dataString.toUtf8().size();
    QString lengthPrefix = QString("REMAINING_DAYS|%1|").arg(len);

    QByteArray prefixToSend = lengthPrefix.toUtf8();
    QByteArray dataToSend = dataString.toUtf8();

    networkManager->sendData(prefixToSend);
    // 调试
    qDebug() << "Sent prefix:" << prefixToSend;
    networkManager->sendData(dataToSend);
    // 调试
    qDebug() << "Sent data:" << dataToSend;
}
//发送查询所有会员信息指令
void Card::on_pushButton_membership_information_clicked()
{
    QByteArray dataToSend = "MEMBERSHIP_INFORMATION|check|";
    networkManager->sendData(dataToSend);
    //ui->listWidget->clear();
    //调试
    qDebug() << "Sent2 data:" << dataToSend;
}


// 处理接收到的数据
void Card::onDataReceived(const QByteArray &data)
{
    QString receivedData;
    // 先尝试使用 UTF - 8 解码
    QTextCodec *utf8Codec = QTextCodec::codecForName("UTF-8");
    receivedData = utf8Codec->toUnicode(data);

    // 简单判断是否为乱码，如果包含大量无法识别的字符，尝试使用 GBK 解码
    if (receivedData.contains(QRegExp("[\\x{FFFD}]+"))) {
        QTextCodec *gbkCodec = QTextCodec::codecForName("GBK");
        receivedData = gbkCodec->toUnicode(data);
    }

    QStringList parts = receivedData.split('|'); // 按 '|' 分割字符串

    // 查找索引
    int registeredIndex = parts.indexOf("REGISTERED");
    int rechargeIndex = parts.indexOf("RECHARGE");
    int remaining_daysIndex = parts.indexOf("REMAINING_DAYS");
    int membership_informationIndex = parts.indexOf("MEMBERSHIP_INFORMATION");

    // 处理登记结果,添加了 this->isVisible() 判断,只在当前界面才显示
    if (registeredIndex != -1 && registeredIndex + 1 < parts.size() && this->isVisible())
    {
        QString result = parts.at(registeredIndex + 1).trimmed();
        if (result == "succeed")
        {
            QMessageBox::information(nullptr, "提示", "登记成功");
        }
        else if (result == "failed")
        {
            QMessageBox::information(nullptr, "提示", "登记失败");
        }
        ui->lineEdit_user->clear();
        ui->lineEdit_phone->clear();
        ui->lineEdit_license->clear();
        ui->lineEdit_days->clear();
    }

    // 处理充值结果
    if (rechargeIndex != -1 && rechargeIndex + 1 < parts.size() && this->isVisible())
    {
        QString result = parts.at(rechargeIndex + 1).trimmed();
        if (result == "succeed")
        {
            QMessageBox::information(nullptr, "提示", "充值成功");
        }
        else if (result == "failed")
        {
            QMessageBox::information(nullptr, "提示", "充值失败");
        }
        ui->lineEdit_phone->clear();
        ui->lineEdit_days->clear();
    }

    // 查询剩余天数的结果
    if (remaining_daysIndex != -1 && remaining_daysIndex + 3 < parts.size())
    {
        QString user = parts.at(remaining_daysIndex + 2).trimmed();
        QString license = parts.at(remaining_daysIndex + 4).trimmed();
        QString days = parts.at(remaining_daysIndex + 6).trimmed();
        ui->lineEdit_user->setText(user);
        ui->lineEdit_license->setText(license);
        ui->lineEdit_days->setText(days);
    }


    // 处理会员信息结果
    if (membership_informationIndex != -1)
    {
        isReceivingMembershipInfo = true;
        membershipCsvData.clear();
    }
    else if (isReceivingMembershipInfo)
    {
        membershipCsvData.append(receivedData);
        // 假设每次接收数据后检查是否数据完整，这里简单以换行符判断
        if (receivedData.contains('\n'))
        {
            isReceivingMembershipInfo = false;
            QStringList lines = membershipCsvData.split('\n');
            if (lines.size() > 0)
            {
                QStringList headers = lines[0].split(',');
                // 设置表格列数
                ui->tableWidget->setColumnCount(headers.size());
                // 设置表头
                ui->tableWidget->setHorizontalHeaderLabels(headers);

                // 设置表格行数
                ui->tableWidget->setRowCount(lines.size() - 1);

                for (int i = 1; i < lines.size(); ++i)
                {
                    QString line = lines[i].trimmed();
                    if (!line.isEmpty())
                    {
                        QStringList fields = line.split(',');
                        for (int j = 0; j < fields.size(); ++j)
                        {
                            QTableWidgetItem *item = new QTableWidgetItem(fields[j]);
                            ui->tableWidget->setItem(i - 1, j, item);
                        }
                    }
                }
            }
            membershipCsvData.clear();
        }
    }
}












